package com.config;

import com.controller.domain.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;
import org.springframework.util.ObjectUtils;

import java.sql.ResultSet;
import java.sql.Statement;

@Order(Integer.MIN_VALUE)
@Component
public class WxRealm implements Realm {

    @Autowired
    JdbcTemplate jdbcTemplate;

    @Override
    public String getName() {
        return "wxRealm";
    }
/**
 * frontend try to encode opendId ,
 * Base64Utils.encodeToUrlSafeString();
 */
    @Override
    public boolean supports(AuthenticationToken token) {
        if(!ObjectUtils.isEmpty(token) && token instanceof BearerToken){
            return true;
        }else{
            return false;
        }
    }

    @Override
    public AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        BearerToken bearerToken = (BearerToken) token;
        String token1 = bearerToken.getToken();
        byte[] bytes = Base64Utils.decodeFromUrlSafeString(token1);
        String openId = new String(bytes);

        String format = String.format("select username,nickname from users where openId='%s'", openId);
        User user = new User();
        jdbcTemplate.execute((Statement stmt)->{
            ResultSet resultSet = stmt.executeQuery(format);
            if(resultSet.next()){
                String username = resultSet.getString(1);
                String nickname = resultSet.getString(2);
                user.setUsername(username);
                user.setNickname(nickname);
            };
            return "";
        });
        SimpleAuthenticationInfo    info = new SimpleAuthenticationInfo(user,"" ,getName());
        return info;
    }
}
